
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flower/model/base_model.dart';
import 'package:flower/model/comment_list.dart';
import 'package:flower/model/flower_info.dart';
import 'package:flower/utils/my_colors.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

import '../../../components/cached_image_widget.dart';
import '../../../components/custom_toast.dart';
import '../../../config/service_url.dart';
import '../../../utils/http_util.dart';

/* 商品详情页 */
class FlowerDetailPage extends StatefulWidget {
  final int flowerId;
  const FlowerDetailPage({super.key, required this.flowerId});

  @override
  State<FlowerDetailPage> createState() => _FlowerDetailState();
}

class _FlowerDetailState extends State<FlowerDetailPage> {
  FlowerData? flower;
  List<String> imagePaths = [];
  List<CommentData> commentList = [];
  bool isFavorite = false;
  int quantity = 1;
  bool inCart = false;
  bool isLoading = true;  // 添加一个加载状态

  @override
  void initState() {
    super.initState();
    queryFlowerInfo();
    queryCommentList();
    queryIsCollection();
    views();
    addToHistory();
  }

  // 获取花卉信息
  void queryFlowerInfo() async {
      // widget.flowerId
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;

    Response result = await HttpUtil.get(getFlowerInfo, queryParameters: map);
    FlowerModel flowerModel = FlowerModel.fromJson(result.data);

    setState(() {
      flower = flowerModel.data;
      imagePaths.add(flowerModel.data!.img1);
      imagePaths.add(flowerModel.data!.img2);
      imagePaths.add(flowerModel.data!.img3);
      isLoading = false;  // 数据加载完成
    });
  }

  // 查询评论列表
  void queryCommentList() async {
    // widget.flowerId
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;

    Response result = await HttpUtil.get(listCommentByFlower, queryParameters: map);
    CommentListModel commentModel = CommentListModel.fromJson(result.data);

    setState(() {
      commentList = commentModel.data!;
    });
  }

  // 查询用户是否收藏了花卉
  void queryIsCollection() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;

    Response result = await HttpUtil.get(isCollection, queryParameters: map);
    BaseModel baseModel = BaseModel.fromJson(result.data);
    isFavorite = baseModel.data;
  }

  // 增加浏览量
  void views() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;

    await HttpUtil.post(addViews, queryParameters: map);
  }

  // 添加到历史记录
  void addToHistory() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;

    await HttpUtil.post(addHistory, queryParameters: map);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("详情展示"),
        titleTextStyle: const TextStyle(fontSize: 16, color: MyColors.normal),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.shopping_cart),
            onPressed: navigateToCart,
          ),
        ],
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator())  // 数据未加载时显示进度指示器
        : Stack(
        children: [
          SizedBox(
            width: MediaQuery.of(context).size.width,
            child: ListView(
              children: [
                // 轮播图
                buildProductPic(),
                // 商品基本信息
                buildProductBaseInfo(),
                const Divider(
                  color: MyColors.line, // 设置分割线的颜色
                  thickness: 1, // 设置分割线的厚度
                  height: 10, // 设置分割线顶部和底部的空白高度
                ),
                // 分享
                buildProductShare(),
                const Divider(
                  color: MyColors.line,
                  thickness: 1,
                  height: 10,
                ),
                // 商品属性和规格
                buildAttributesInfo(context),
                const Divider(
                  color: MyColors.line,
                  thickness: 1,
                  height: 10,
                ),
                //评价信息
                buildPinJiaInfo(),
                const Divider(
                  color: MyColors.line,
                  thickness: 1,
                  height: 10,
                ),
                //底部按钮
                buildFooter(context),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void navigateToCart()  {
    Navigator.pushNamed(context, '/cart');
  }

  // 花卉图片
  Widget buildProductPic() {
    return Center(
      child: CarouselSlider(
        items: imagePaths.map((imagePath) {
          return Container(
            alignment: Alignment.topCenter,
            child: CachedImageWidget(
              double.infinity,
              double.infinity,
              imagePath,
              fit: BoxFit.cover,
              borderRadius: BorderRadius.circular(10),
            ),
          );
        }).toList(),
        options: CarouselOptions(
          aspectRatio: 33 / 20, // 宽高比
          autoPlay: false, // 关闭自动轮播
          enlargeCenterPage: true,
        ),
      ),
    );
  }

  // 信息展示
  void addToCart() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;
    map["number"] = quantity;
    map["amount"] = quantity * flower!.price;
    Response result = await HttpUtil.post(addFlowerToCart, queryParameters: map);
    BaseModel baseModel = BaseModel.fromJson(result.data);
    if (baseModel.code == 1) {
      CustomToast.showSuccessToast("添加成功");
      setState(() {
        inCart = true;
      });
    }
  }

  // 商品数量加一
  void increaseQuantity() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;
    map["number"] = 1;
    map["amount"] = flower!.price;
    Response result = await HttpUtil.post(addFlowerToCart, queryParameters: map);
    BaseModel baseModel = BaseModel.fromJson(result.data);
    if (baseModel.code == 1) {
      setState(() {
        quantity++;
      });
    }
  }

  // 商品数量减一
  void decreaseQuantity() async {
    if (quantity > 1) {
      Map<String, dynamic> map = <String, dynamic>{};
      map["fid"] = widget.flowerId;
      map["number"] = -1;
      map["amount"] = flower!.price * -1;
      Response result = await HttpUtil.post(addFlowerToCart, queryParameters: map);
      BaseModel baseModel = BaseModel.fromJson(result.data);
      if (baseModel.code == 1) {
        setState(() {
          quantity--;
        });
      }
    }
  }

  // 点击收藏
  void toggleFavorite() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["fid"] = widget.flowerId;
    map["status"] = !isFavorite;
    Response result = await HttpUtil.post(likeOrCancel, queryParameters: map);
    BaseModel baseModel = BaseModel.fromJson(result.data);
    if (baseModel.code == 1) {
      setState(() {
        isFavorite = !isFavorite;
      });
    }
  }

  Container buildProductBaseInfo() {
    return Container(
      color: MyColors.white,
      padding: const EdgeInsets.all(15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(flower!.name,
                        style: const TextStyle(
                            fontSize: 16,
                            color: MyColors.normal)),
                    Text(flower!.ename,
                        style: const TextStyle(
                            fontSize: 14,
                            color: MyColors.title)),
                    SizedBox(
                      height: 32,
                      child: Row(
                        children: [
                          const Text("¥ ",
                              style: TextStyle(fontSize: 18, color: MyColors.price)),
                          Text("${flower?.price}",
                              style: const TextStyle(fontSize: 17, color: MyColors.price)),
                          const Text(" / ",
                              style: TextStyle(fontSize: 18, color: MyColors.price)),
                          Text("${flower?.unit}",
                              style: const TextStyle(fontSize: 15, color: MyColors.price)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Column(
                children: [
                  Row(
                    children: [
                      IconButton(
                        icon: Icon(
                          isFavorite ? Icons.favorite : Icons.favorite_border,
                          color: isFavorite ? MyColors.status : MyColors.title,
                        ),
                        onPressed: toggleFavorite,
                      ),
                      inCart
                          ? Row(
                        children: [
                          IconButton(
                            icon: const Icon(Icons.remove),
                            onPressed: decreaseQuantity,
                          ),
                          Text('$quantity'),
                          IconButton(
                            icon: const Icon(Icons.add),
                            onPressed: increaseQuantity,
                          ),
                        ],
                      )
                          : ElevatedButton.icon(
                        onPressed: addToCart,
                        icon: const Icon(Icons.add),
                        label: const Text("加入购物车"),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 15),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("销量: ${flower?.sales}",
                  style: const TextStyle(fontSize: 14, color: MyColors.title)),
              Text("库存: ${flower?.inventory}",
                  style: const TextStyle(fontSize: 14, color: MyColors.title)),
              Text("浏览量: ${flower?.views}",
                  style: const TextStyle(fontSize: 14, color: MyColors.title)),
            ],
          ),
        ],
      ),
    );
  }
  //分享
  Container buildProductShare() {
    var boxDecoration = BoxDecoration(
        border: Border.all(
          width: 1,
          color: MyColors.boyPink,
        ),
        borderRadius: const BorderRadius.all(Radius.circular(5)));
    return Container(
      height: 40,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: [
          Container(
            decoration: boxDecoration,
            child: Row(
              children: [
                Image.asset(
                  "assets/images/five.png",
                  height: 16,
                  width: 17,
                ),
                const Text("优惠", style: TextStyle(fontSize: 14, color: MyColors.boyPink)),
              ],
            ),
          ),
          const Expanded(
              child: Text(" 该商品分享可领49减10红包", style: TextStyle(fontSize: 14, color: MyColors.boyPink))),
          const Text("立即分享", style: TextStyle(fontSize: 14, color: MyColors.boyPink)),
          Image.asset(
            "assets/images/right_arrow1.png",
            height: 13,
            width: 13,
            color: MyColors.boyPink,
          )
        ],
      ),
    );
  }

  // 商品属性和规格
  Container buildAttributesInfo(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(15),
      color: MyColors.white,
      child: Column(
        children: [
          buildTxt("花语    ", "查看", 1, context),
          buildTxt("优惠券  ", "领取优惠券", 2, context),
          buildTxt("促销活动", "暂无优惠", 3, context),
          buildTxt("商家服务", "无忧退货 · 快速退款 · 免费包邮 ·", 4, context),
        ],
      ),
    );
  }

  //商品属性和规格InkWell
  InkWell buildTxt(String title, String value, int flag, BuildContext context) {
    var border = const BorderSide(
        width: 1, color: MyColors.description);
    var boxDecoration = BoxDecoration(
      border: Border(bottom: border),
    );
    return InkWell(
      onTap: () {
        _openBottomSheetWithInfo(context, title);
      },
      child: Container(
        decoration: boxDecoration,
        height: 47,
        child: Row(
          children: [
            Text(title,
                style: const TextStyle(fontSize: 14, color: MyColors.sharebk)),
            const SizedBox(
              width: 20,
            ),
            Expanded(
              child: Text(value,
                  style: const TextStyle(fontSize: 14, color: MyColors.normal)),
            ),
            Image.asset(
              "assets/images/right_arrow1.png",
              height: 13,
              width: 13,
            )
          ],
        ),
      ),
    );
  }

  // 评价信息
  Container buildPinJiaInfo() {
    return Container(
      // 这里是你的容器布局
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(
              '评价 (${commentList.length})', // 标题和评论数
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          commentList.isEmpty
              ? const Padding(
            padding: EdgeInsets.all(8.0),
            child: Text('还没有评论哦~'), // 没有评论时显示的文本
          )
              : ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: commentList.length,
            itemBuilder: (context, index) {
              CommentData comment = commentList[index];
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        CircleAvatar(
                          backgroundImage: NetworkImage(comment.avatar), // 用户头像
                          radius: 20,
                        ),
                        SizedBox(width: 8),
                        Text(
                          comment.nickname, // 用户昵称
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                        const Spacer(),
                        buildStars(comment.score), // 星级评分
                      ],
                    ),
                    const SizedBox(height: 8),
                    Text(
                      comment.content, // 评论内容
                      style: const TextStyle(fontSize: 16),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      comment.createTime, // 评论时间
                      style: const TextStyle(color: MyColors.border),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  // 评论星数
  Widget buildStars(int stars) {
    return Row(
      children: List.generate(5, (index) {
        return Icon(
          index < stars ? Icons.star : Icons.star_border,
          color: MyColors.status,
          size: 16,
        );
      }),
    );
  }

  // 参数栏点击
  void _openBottomSheetWithInfo(BuildContext context, String title) {
    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return DraggableScrollableSheet(
          expand: false,
          builder: (BuildContext context, ScrollController scrollController) {
            if (title.contains("花语")) {
              return buildFlowerParams();
            }
            if (title.contains("优惠券")) {
              return buildCouponList(scrollController);
            }
            if (title.contains("促销活动")) {
              return buildPromotion("title", "value", scrollController);
            }
            if (title.contains("商家服务")) {
              return buildMerchantServices("title", "value", scrollController);
            }
            if (title.contains("添加到购物车")) {
              return addToShoppingCart();
            }
            return buildMerchantServices("title", "value", scrollController);
          },
        );
      },
    );
  }

  Container addToShoppingCart() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      height: 200,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '${flower?.name}',
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  IconButton(
                    onPressed: () {
                      setState(() {
                        if (quantity > 1) quantity--;
                      });
                    },
                    icon: const Icon(Icons.remove),
                  ),
                  Text(
                    quantity.toString(),
                    style: const TextStyle(fontSize: 16),
                  ),
                  IconButton(
                    onPressed: () {
                      setState(() {
                        quantity++;
                      });
                    },
                    icon: const Icon(Icons.add),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {
              // Add further actions here, such as adding to cart logic
              Navigator.pop(context);
            },
            child: const Center(child: Text('确认添加')),
          ),
        ],
      ),
    );
  }

  // 花语
  Container buildFlowerParams() {
    return Container(
      padding: const EdgeInsets.all(30),
      child: Text(
        flower!.meaning,
        style: TextStyle(
          fontSize: 16,
          color: MyColors.normal,
        ),
      ),
    );
  }

  // 优惠券列表
  ListView buildCouponList(ScrollController controller) {
    return ListView.builder(
        controller: controller,
        shrinkWrap: true,
        itemCount: 10,
        itemBuilder: (context, index) {
          return Container(
              padding: const EdgeInsets.all(15),
              decoration: const BoxDecoration(
                  border: Border(
                      bottom: BorderSide(width: 1, color: MyColors.border))),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("全品类通用券",
                                style: TextStyle(
                                    fontSize: 16, color: MyColors.normal)),
                            Text("有效期至2023-11-30 00:00:00",
                                style: TextStyle(
                                    fontSize: 12, color: MyColors.title)),
                          ],
                        ),
                      ),
                      Column(
                        children: [
                          Row(
                            children: [
                              Text("￥",
                                  style: TextStyle(
                                      fontSize: 17, color: MyColors.price)),
                              Text("10",
                                  style: TextStyle(
                                      fontSize: 22, color: MyColors.price)),
                            ],
                          ),
                          Text("满100可用",
                              style:
                              TextStyle(fontSize: 13, color: MyColors.line)),
                        ],
                      )
                    ],
                  ),
                  Container(
                    height: 5,
                  ),
                  const Text("全场通用",
                      style: TextStyle(fontSize: 12, color:MyColors.title)),
                ],
              ));
        });
  }

  // 促销活动
  ListView buildPromotion(String title, String value, ScrollController controller) {
    return ListView.builder(
        controller: controller,
        shrinkWrap: true,
        itemCount: 10,
        itemBuilder: (context, index) {
          return Container(
              padding: const EdgeInsets.all(15),
              decoration: const BoxDecoration(
                  border: Border(
                      bottom: BorderSide(width: 1, color: MyColors.border))),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("全品类通用券",
                                style: TextStyle(
                                    fontSize: 16, color: MyColors.normal)),
                            Text("有效期至2023-11-30 00:00:00",
                                style: TextStyle(
                                    fontSize: 12, color: MyColors.title)),
                          ],
                        ),
                      ),
                      Column(
                        children: [
                          Row(
                            children: [
                              Text("￥",
                                  style: TextStyle(
                                      fontSize: 17, color: MyColors.price)),
                              Text("10",
                                  style: TextStyle(
                                      fontSize: 22, color: MyColors.price)),
                            ],
                          ),
                          Text("满100可用",
                              style:
                              TextStyle(fontSize: 13, color: MyColors.line)),
                        ],
                      )
                    ],
                  ),
                  Container(
                    height: 5,
                  ),
                  const Text("全场通用",
                      style: TextStyle(fontSize: 12, color:MyColors.title)),
                ],
              ));
        });
  }

  // 商家服务
  ListView buildMerchantServices(String title, String value, ScrollController controller) {
    return ListView.builder(
        controller: controller,
        shrinkWrap: true,
        itemCount: 1,
        itemBuilder: (context, index) {
          return Container(
            padding: const EdgeInsets.all(30),
            margin: const EdgeInsets.only(bottom: 50),
            child: const Text("无忧退货 · 快速退款 · 免费包邮 ·",
                style: TextStyle(fontSize: 14, color: MyColors.normal)),
          );
        });
  }

  //底部按钮购物车收藏评论
  InkWell buildFooter(BuildContext context) {
    return InkWell(
      child: Container(
        margin: const EdgeInsets.only(bottom: 5),
        height: 40,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: MyColors.bottom, // 替换成你想要的背景颜色
          borderRadius: BorderRadius.circular(20),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 加入购物车部分
            InkWell(
              onTap: () {
                print('加入购物车');
                // addToCart();
              },
              child: const Row(
                children: [
                  Icon(
                    Icons.shopping_cart,
                    color: MyColors.white,
                    size: 20,
                  ),
                  SizedBox(width: 8),
                  Text(
                    '加入购物车',
                    style: TextStyle(
                      color: MyColors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 44), // 调整购物车和收藏之间的间距

            // 收藏部分
            InkWell(
              onTap: () {
                print('收藏');
              },
              child: const Row(
                children: [
                  Icon(
                    Icons.favorite,
                    color: MyColors.white,
                    size: 20,
                  ),
                  SizedBox(width: 8),
                  Text(
                    '收藏',
                    style: TextStyle(
                      color: MyColors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 44), // 调整收藏和评论之间的间距

            // 评论部分
            InkWell(
              onTap: () {
              },
              child: const Row(
                children: [
                  Icon(
                    Icons.comment,
                    color: MyColors.white,
                    size: 20,
                  ),
                  SizedBox(width: 8),
                  Text(
                    '评论',
                    style: TextStyle(
                      color: MyColors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

}
